package cn.chint.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;



/**
 * HTTPClient 工具类
 * 
 * @author Lynch 2014-09-15
 *
 */
public class HTTPClientUtils {

	//private final static String CONTENT_TYPE_TEXT_JSON = "text/json";
	
	public static void main(String[] agrs) throws Exception{
//		JSONObject jsonObj = new JSONObject();
//    	jsonObj.put("userId", 42);
//    	jsonObj.put("programId", 290);
//    	jsonObj.put("shareSource", 0);
//		
//    	String url ="https://blistening.cn//programResource/myProgramShare";
//    	try{
//    		String res = HTTPClientUtils.postRequest(url, jsonObj.toString());
//    		
//    		System.out.println(res);
//    	}catch(Exception e){
//    		e.printStackTrace();
//    	}
    	
		try{
		    Map<String, Object> param=new HashMap<String, Object>();
	        param.put("startTime", new Date());
	        param.put("endTime", new Date());
	        
	        Map<String, Object> headers=new HashMap<String, Object>();
	        String result = postForAPP("http://127.0.0.1:8080/gox-ttbt/web/query/recharge", "POST", param, headers);
	        System.out.println(result);

		}catch(Exception e){
    		e.printStackTrace();
    	}
	}
	
	/**
     * 发送  post 请求
     * @param url 请求地址，如 http://www.baidu.com
     * @param param相关参数, 模拟form 提交
     * @return
     * @throws Exception 
     */
    public static String postForAPP(String url, String sMethod, Map<String, Object> param, Map<String, Object> headers) throws Exception {
        //目前HttpClient最新版的实现类为CloseableHttpClient
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpEntity entity=null;
        try {
            if(param != null) {
                //建立Request的对象，一般用目标url来构造，Request一般配置addHeader、setEntity、setConfig
                HttpPost req = new HttpPost(url);
                entity=new UrlEncodedFormEntity(createParam(param), Consts.UTF_8);
                //setHeader,添加头文件
                Set<String> keys = headers.keySet();
                for (String key : keys) {
                    req.setHeader(key, headers.get(key).toString());
                }
                //setConfig,添加配置,如设置请求超时时间,连接超时时间
                RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
                req.setConfig(reqConfig);
                //setEntity,添加内容
                req.setEntity(entity);
                //执行Request请求,CloseableHttpClient的execute方法返回的response都是CloseableHttpResponse类型
                //其常用方法有getFirstHeader(String)、getLastHeader(String)、headerIterator（String）取得某个Header name对应的迭代器、getAllHeaders()、getEntity、getStatus等
                response = client.execute(req);
                try{
	                entity =  response.getEntity();
	                int httpStatusCode = response.getStatusLine().getStatusCode() ;
	                System.out.println(httpStatusCode);
	                //用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
	                String result= EntityUtils.toString(entity, "UTF-8");
	                return result;
                }catch(Exception e){
                	e.printStackTrace();
                }finally{
                	response.close();
                }
            }
            return null;
        } catch(Exception e) {
             e.printStackTrace();
             throw e;
        }finally{
            //一定要记得把entity fully consume掉，否则连接池中的connection就会一直处于占用状态
            //EntityUtils.consume(entity);
            client.close();
        }
		
    }
    private static List<NameValuePair> createParam(Map<String, Object> param) {
        //建立一个NameValuePair数组，用于存储欲传送的参数
    	List<NameValuePair> nvps = new ArrayList <NameValuePair>();
        if(param != null) {
            for(String k : param.keySet()) {
                nvps.add(new BasicNameValuePair(k, param.get(k).toString()));
            }
        }
        return nvps;
    }


	
    public static String getRequest(String url) throws Exception{
        
		CloseableHttpClient client = HttpClients.createDefault();

		try{
		
			RequestConfig requestConfig = RequestConfig.custom()
	            .setConnectTimeout(50000).setConnectionRequestTimeout(10000)
	            .setSocketTimeout(50000).build(); 
	
	
			HttpGet httpPost = new HttpGet(url);
	
	        httpPost.setConfig(requestConfig);
	        
			CloseableHttpResponse response = client.execute(httpPost);
			try{
				int statuscode = response.getStatusLine().getStatusCode();
				System.out.println(statuscode);
				
				String result = EntityUtils.toString(response.getEntity(),"UTF-8");//获得返回的结果
				return result;
			}catch(Exception e){
				e.printStackTrace();
				throw e;
			}finally{
				response.close();
			}
			
			
			
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			client.close();
		}
    

}
	
    
    public static String postRequest(String url,String json) throws IOException {
        
    		CloseableHttpClient client = HttpClients.createDefault();
            
    		try{
	    		RequestConfig requestConfig = RequestConfig.custom()
	                .setConnectTimeout(50000).setConnectionRequestTimeout(10000)
	                .setSocketTimeout(50000).build();
	
		
	    		HttpPost httpPost = new HttpPost(url);
	
		        httpPost.setConfig(requestConfig);
		        
		        httpPost.setHeader("Content-type", "application/json");
				httpPost.setEntity(new StringEntity(json, "UTF-8"));
				CloseableHttpResponse response = client.execute(httpPost);
				try{
					int statuscode = response.getStatusLine().getStatusCode();
					System.out.println(statuscode);
					
					String result = EntityUtils.toString(response.getEntity(),"UTF-8");//获得返回的结果
					return result;
				}catch(Exception e){
					e.printStackTrace();
					throw e;
				}finally{
					response.close();
	    		}
				
				
				
				
    		}catch(Exception e){
    			e.printStackTrace();
    			//throw e;
    		}finally{
    			client.close();
    		}
			return json;
			

        

    }




}
